import React, {FC, useCallback, useContext, useEffect, useMemo, useState} from 'react';
import "./index.less";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import default_art_cover from "@/assets/default_art_cover.png";
import {FormattedMessage, history, Link, NavLink, useParams} from "@@/exports";
import HxIcon from "@/components/HxIcon";
import {Button, Image, message, Space, Tabs, Typography} from "antd";
import JournalInfoMeta from "@/pages/JournalPage/JournalDetail/commons/JournalInfoMeta";
import {useRequest} from "ahooks";
import * as API from "@/services";
import {JournalDetailContext} from "@/pages/JournalPage/JournalDetail/commons/JournalDetailContext";
import {Outlet} from "umi";
import {correspVal} from "@/utils/biz";
import {JournalPeriodDisplayType} from "@/pages/JournalPage/JournalDetail/commons/JournalPeriodList";
import queryString from "query-string";
import lodash from "lodash";
import classNames from "classnames";
import useBreakpoint from "antd/es/grid/hooks/useBreakpoint";

interface JournalDetailProps {
}

const JournalDetail: FC<JournalDetailProps> = (props) => {
  const {setLayoutBgClassName} = useContext(HxConfigContext)
  const screens = useBreakpoint();
  const isMobile = !(screens.lg || screens.xxl || screens.xl);

  useEffect(() => {
    setLayoutBgClassName?.("bg-bule-433");
    return () => {
      setLayoutBgClassName?.(undefined);
    }
  }, []);
  const {isZhCN} = useContext(HxConfigContext)
  const {journalId} = useParams();
  //const [journalPeriodDisplayType, setJournalPeriodDisplayType] = useState<JournalPeriodDisplayType>("card");

  //从请求params中获取journalPeriodDisplayType
  const journalPeriodDisplayType: JournalPeriodDisplayType = useMemo(() => {
    const {periodDisplayType} = queryString.parse(location?.search);
    let ret = lodash.isArray(periodDisplayType) ? periodDisplayType[0] : periodDisplayType;
    if (!periodDisplayType) {
      ret = null;
    }
    return ret === "tree" ? "tree" : "card";
  }, [location?.search]);

  const setJournalPeriodDisplayType = useCallback((displayType: JournalPeriodDisplayType) => {
    history.push({
      pathname: ``,
      search: queryString.stringify({
        ...queryString.parse(location.search),
        periodDisplayType: displayType,
      })
    });
  }, [location?.search]);


  const journalReq = useRequest(() => API.queryFrontJournal(journalId!), {
    ready: !!journalId,
    refreshDeps: [journalId],
  });

  const data = journalReq.data?.data;
  const isCn = data?.languageType === "CN";   //是否中文刊

  const introduction = correspVal(isZhCN, data?.journalBreviaryIntroductionCn, data?.journalBreviaryIntroductionEn);

  const navActive = useCallback((props: {
    isActive: boolean;
  }) => {
    return props.isActive ? 'active' : undefined;
  }, []);


  return (
    <JournalDetailContext.Provider value={{
      journal: data,
      journalId: journalId,
      journalPeriodDisplayType,
      setJournalPeriodDisplayType,
    }}>
      <div className={classNames("journal-detail-container", {"journal-detail-container-hidden": !data})}>
        <div className={classNames("journal-detail-header")}>
          <div className={"journal-detail-info"}>
            <div className={"journal-detail-info-cover"}>
              <Image src={data?.journalCoverPathUrl} fallback={default_art_cover} preview={false}/>
            </div>
            <div className={"journal-detail-info-body"}>
              <div className={"journal-detail-info-header"}>
                <div className={"journal-detail-info-title"}>
                  <Typography.Paragraph
                    ellipsis={{
                      rows: 1,
                      tooltip: correspVal(isZhCN, data?.journalNameCn, data?.journalNameEn)
                    }}
                  >
                    {correspVal(isZhCN, data?.journalNameCn, data?.journalNameEn)}
                  </Typography.Paragraph>
                </div>
                <JournalInfoMeta className={classNames("journal-detail-info-meta", {"journal-detail-info-meta-en": !isCn})} journal={data}/>
                {
                  isCn && (
                    <div className={"journal-detail-info-content"}>
                      <Typography.Paragraph
                        ellipsis={{
                          rows: 3,
                          tooltip: {
                            title: introduction,
                            trigger: "click",
                            styles: {
                              root: {
                                maxWidth: 1218
                              }
                            },
                          },
                          expandable: false
                        }}
                      >
                        {introduction}
                      </Typography.Paragraph>
                    </div>
                  )
                }

              </div>

              <div className={"journal-detail-info-footer"}>
                <Space size={16} direction={isMobile ? "vertical" : "horizontal"} className={"journal-footer-btns-wrapper"}>
                  <Link to={`/mall/product/${data?.id}`} className={"journal-footer-btn"}>
                    <Button color={"orange"} variant="solid" block={isMobile}>
                      <FormattedMessage id="journal.subscription"/>
                    </Button>
                  </Link>
                  {
                    isCn ? (
                      <>
                        <a href={`https://cluster.hxyx.com`} target="_blank" className={"journal-footer-btn"}>
                          <Button color={"green"} variant="solid" block={isMobile}>
                            <FormattedMessage id="journal.submission-review-porta"/>
                          </Button>
                        </a>
                        <Link to={`/journal/${data?.id}/guide`} className={"journal-footer-btn"}>
                          <Button color={"default"} variant={isMobile ? "solid" : "link"} className={"submission-guidelines-btn"} block={isMobile}>
                            <HxIcon type={"hxicon-dengpao"}/> <FormattedMessage id="journal.instructions-for-authors"/>
                          </Button>
                        </Link>
                      </>
                    ) : (
                      <a href={data?.externalWebsite || "#"}
                            target="_blank"
                            className={"journal-footer-btn"}
                            onClick={(e) => {
                              if (!data?.externalWebsite) {
                                e.preventDefault(); // 阻止默认跳转行为
                                message.warning("当前期刊国外合作出版商网站地址未配置"); // 提示用户
                              }
                            }}
                      >
                        <Button color={"green"} variant="solid" block={isMobile}>
                          <FormattedMessage id="journal.jump-to-overseas-publishers-sites"/>
                        </Button>
                      </a>
                    )
                  }
                </Space>
              </div>
            </div>
          </div>
        </div>
        <div className={"journal-detail-content"}>
          {/*<HxCyTabs
          tabBarExtraContent={{
            right: <div>
              <Link to={`/journal/${data?.id}`} className={"journal-wx-btn"}>
                <HxIcon type={"hxicon-weixin1"}/> 微信公众号
              </Link>
            </div>
          }}
          items={[
            {label: "本刊首页", key: "home", children: <JournalDetailHome/>},
            {label: "期刊简介", key: "intro", children: <JournalIntroduction/>},
            {label: "过刊浏览", key: "brower", children: <JournalArchiveBrowsing/>},
            {label: "模板文档下载", key: "download", children: <JournalDocDownload/>},
            {label: "统计数据", key: "stats", children: <JournalStatistic/>},
          ]}
        />*/}
          <div className={classNames("journal-detail-content-navs-wrap")}>
            <ul className={"journal-detail-content-navs"}>
              {
                isCn ? (
                  <>
                    <li><NavLink to={`/journal/${data?.id}/home`} end={true} className={navActive}><FormattedMessage id="journal.home"/></NavLink></li>
                    <li><NavLink to={`/journal/${data?.id}/intro`} end={true} className={navActive}><FormattedMessage id="journal.intro"/></NavLink></li>
                    <li><NavLink to={`/journal/${data?.id}/archive`} end={true} className={navActive}><FormattedMessage id="journal.archive"/></NavLink></li>
                    <li><NavLink to={`/journal/${data?.id}/download`} end={true} className={navActive}><FormattedMessage id="journal.temp-download"/></NavLink>
                    </li>
                    <li><NavLink to={`/journal/${data?.id}/stats`} end={true} className={navActive}><FormattedMessage id="journal.stats"/></NavLink></li>
                    <li><NavLink to={`/journal/${data?.id}/guide`} end={true} className={navActive}><FormattedMessage id="journal.guide"/></NavLink></li>
                  </>
                ) : (
                  <>
                    <li><NavLink to={`/journal/${data?.id}/home`} end={true} className={navActive}><FormattedMessage id="journal.intro"/></NavLink></li>
                  </>
                )
              }
            </ul>

            <div>
              {
                /*TODO 微信公众号二维码*/
                data?.wxMp && (
                  <Link to={`/journal/${data?.id}`} className={"journal-wx-btn"}>
                    <HxIcon type={"hxicon-weixin1"}/> <FormattedMessage id="app.wechat-official"/>
                  </Link>
                )
              }
            </div>
          </div>

          <Outlet/>
        </div>
      </div>
    </JournalDetailContext.Provider>
  );
};

export default JournalDetail;
